﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using BitPortal.Models;
using BitPortal.Business;
using System.Web.Security;
using BitPortal.Utils;

namespace BitPortal.Admin.Account.Admin.Module
{
    public partial class AdminAddEdit : Controls.BaseAdminControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            mtslRoles.Items.Clear();
            ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
            List<aspnet_Roles> roles = new List<aspnet_Roles>();
            if (Roles.IsUserInRole("RootAdmin"))
            {
                roles = (new ExtendedBitPortalEntities()).aspnet_Roles.ToList();
            }
            else
            {
                roles = (new ExtendedBitPortalEntities()).aspnet_Users.SingleOrDefault(ent => ent.UserId == BitContext.Current.LoginUser).aspnet_Roles.OrderBy(ent => ent.RoleName).ToList();
            }
            foreach (var r in roles)
            {
                mtslRoles.Items.Add(new Ext.Net.ListItem(r.RoleName + " - " + r.Description, r.RoleName));
            }
            mtslRoles.DataBind();
        }

        public void BindData(string account)
        {
            if (account != null)
            {
                MembershipUser user = Membership.GetUser(account);
                if (user != null)
                {
                    txtID.Text = user.UserName;
                    txtUserName.Text = user.UserName;
                    txtUserName.Enabled = false;
                    txtUserName.Disabled = true;
                    txtEmail.Text = user.Email;
                    btnSetPassword.Hidden = false;
                    //info
                    UserInfo uInfo = (new ExtendedBitPortalEntities()).UserInfos.SingleOrDefault(ent => ent.aspnet_Users.UserName == account);
                    if (uInfo != null)
                    {
                        txtFirstName.Text = uInfo.FirstName;
                        txtLastName.Text = uInfo.LastName;
                        txtAddress.Text = uInfo.Address;
                        if (uInfo.Bithday != null)
                        {
                            dateBirthday.SelectedDate = (DateTime)uInfo.Bithday;
                        }
                        if (uInfo.Gender == true)
                        {
                            cbGender.SelectedIndex = 0;
                        }
                        else
                        {
                            cbGender.SelectedIndex = 1;
                        }
                    }
                    mtslRoles.SelectedItems.Clear();
                    foreach (string r in Roles.GetRolesForUser(user.UserName))
                    {
                        mtslRoles.SelectedItems.Add(new SelectedListItem(r));
                    }
                    if (!string.IsNullOrEmpty(Request.QueryString["Role"])) mtslRoles.SelectedItems.Add(new SelectedListItem(Request.QueryString["Role"]));
                    mtslRoles.UpdateSelection();

                    btnInsert.Hidden = true;
                    btnUpdate.Hidden = false;
                    Panel1.Title = "Sửa thông tin admin";
                }

            }
            else
            {
                txtID.Text = "";
                txtUserName.Enabled = true;
                btnSetPassword.Hidden = true;
                txtUserName.Text = txtEmail.Text = txtPassword.Text = txtFirstName.Text = txtLastName.Text = txtAddress.Text = dateBirthday.Text = "";
                mtslRoles.SelectedItems.Clear();
                if (!string.IsNullOrEmpty(Request.QueryString["Role"])) mtslRoles.SelectedItems.Add(new SelectedListItem(Request.QueryString["Role"]));
                mtslRoles.UpdateSelection();
                btnInsert.Hidden = false;
                btnUpdate.Hidden = true;
                Panel1.Title = "Thêm thông tin admin";
            }

        }

        protected void btnInsert_Click(object sender, DirectEventArgs e)
        {
            try
            {
            PermissionBLL.CheckRoleThrowException("AccountInsert");
            UserInfo uInfo = new UserInfo()
            {
                FirstName = txtFirstName.Text,
                LastName = txtLastName.Text,
                Gender = cbGender.SelectedIndex == 0,
                Address = txtAddress.Text,
                Bithday = dateBirthday.SelectedDate < new DateTime(1990, 1, 1) ? null : (DateTime?)dateBirthday.SelectedDate
            };
            UserBLL.CreateUser(txtUserName.Text.Trim(), txtPassword.Text.Trim(), txtEmail.Text.Trim(), uInfo, mtslRoles.SelectedItems.Select(ent => ent.Value).ToArray());
            if (ckSendEmail.Checked)
            {
                try
                {
                    EmailUtils.SendEmail(PortalConfigBLL.GetValueByName("DefaultAdminEmail").ToString(),
                        new string[] { txtEmail.Text },
                        PortalConfigBLL.GetValueByName("Template.EmailCreateAccount.Header").ToString(),
                        PortalConfigBLL.GetValueByName("Template.EmailCreateAccount").ToString().Replace("{LastName}", txtLastName.Text).Replace("{FirstName}", txtFirstName.Text).Replace("{UserName}", txtUserName.Text).Replace("{Password}", txtPassword.Text)
                        );
                }
                catch (Exception ex)
                {
                    (this.Page as Controls.BaseAdminPage).ShowNotification("Có lỗi khi gửi email cho khách hàng: " + ex.Message);
                }
                try
                {
                    EmailUtils.SendEmail(PortalConfigBLL.GetValueByName("DefaultAdminEmail").ToString(),
                        new string[] { Membership.GetUser().Email },
                        PortalConfigBLL.GetValueByName("Template.EmailCreateAccount.Header").ToString(),
                        PortalConfigBLL.GetValueByName("Template.EmailCreateAccount").ToString().Replace("{LastName}", txtLastName.Text).Replace("{FirstName}", txtFirstName.Text).Replace("{UserName}", txtUserName.Text).Replace("{Password}", txtPassword.Text)
                        );
                }
                catch (Exception ex)
                {
                    (this.Page as Controls.BaseAdminPage).ShowNotification("Có lỗi khi gửi email forward cho admin: " + ex.Message);
                }

            }
            (this.Page as Controls.BaseAdminPage).ShowNotification("Thêm người dùng thành công");
            ReloadTargetData();
            }
            catch (Exception ex)
            {
                (this.Page as Controls.BaseAdminPage).ShowMessage(ex.Message);
            }
        }

        protected void btnUpdate_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("AccountEdit");
                UserInfo uInfo = new UserInfo()
                {
                    FirstName = txtFirstName.Text,
                    LastName = txtLastName.Text,
                    Gender = cbGender.SelectedIndex == 0,
                    Address = txtAddress.Text,
                    Bithday = dateBirthday.SelectedDate > new DateTime(1990, 1, 1) ? (DateTime?)dateBirthday.SelectedDate : null
                };

                UserBLL.UpdateUser(txtID.Text, txtEmail.Text.Trim(), uInfo, mtslRoles.SelectedItems.Select(ent => ent.Value).ToArray());
                (this.Page as Controls.BaseAdminPage).ShowNotification("Cập nhật người dùng thành công");
                ReloadTargetData();
            }
            catch (Exception ex)
            {
                (this.Page as Controls.BaseAdminPage).ShowMessage(ex.Message);
            }
        }

        protected void btnSetPassword_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("AccountEdit");
                MembershipUser user = Membership.GetUser(txtID.Text);
                if (user != null && !string.IsNullOrEmpty(txtPassword.Text))
                {
                    string temp = user.ResetPassword();
                    if (user.ChangePassword(temp, txtPassword.Text))
                    {
                        if (ckSendEmail.Checked)
                        {
                            try
                            {
                                EmailUtils.SendEmail(PortalConfigBLL.GetValueByName("DefaultAdminEmail").ToString(),
                                    new string[] { txtEmail.Text },
                                    PortalConfigBLL.GetValueByName("Template.EmailResetPassword.Header").ToString(),
                                    PortalConfigBLL.GetValueByName("Template.EmailResetPassword").ToString().Replace("{LastName}", txtLastName.Text).Replace("{FirstName}", txtFirstName.Text).Replace("{UserName}", txtUserName.Text).Replace("{Password}", txtPassword.Text)
                                    );
                            }
                            catch (Exception ex)
                            {
                                (this.Page as Controls.BaseAdminPage).ShowNotification("Có lỗi khi gửi email cho khách hàng: " + ex.Message);
                            }
                            try
                            {
                                EmailUtils.SendEmail(PortalConfigBLL.GetValueByName("DefaultAdminEmail").ToString(),
                                    new string[] { Membership.GetUser().Email },
                                    PortalConfigBLL.GetValueByName("Template.EmailResetPassword.Header").ToString(),
                                    PortalConfigBLL.GetValueByName("Template.EmailResetPassword").ToString().Replace("{LastName}", txtLastName.Text).Replace("{FirstName}", txtFirstName.Text).Replace("{UserName}", txtUserName.Text).Replace("{Password}", txtPassword.Text)
                                    );
                            }
                            catch (Exception ex)
                            {
                                (this.Page as Controls.BaseAdminPage).ShowNotification("Có lỗi khi gửi email forward cho admin: " + ex.Message);
                            }

                        }
                        (this.Page as Controls.BaseAdminPage).ShowNotification("Cập nhật mật khẩu người dùng thành công ");
                    }
                }
            }
            catch (Exception ex)
            {
                (this.Page as Controls.BaseAdminPage).ShowMessage(ex.Message);
            }

        }
    }
}